package com.javacv.plus.extensions.audio.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.audio.AudioProcessor;
import com.javacv.plus.extensions.audio.AudioResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

/**
 * 音频压缩步骤
 */
@Slf4j
public class AudioCompressStep implements ProcessorStep<AudioProcessor, AudioResult> {
    private final String quality;

    public AudioCompressStep(String quality) {
        this.quality = quality;
    }

    @Override
    public AudioResult execute(AudioProcessor processor, ProcessorContext context) throws Exception {
        log.info("Compressing audio with quality: {}", quality);

        FFmpegFrameGrabber grabber = (FFmpegFrameGrabber) context.getAttribute("grabber");
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
                "temp_compress.mp3",
                grabber.getAudioChannels(),
                grabber.getSampleRate()
        );

        // 设置压缩参数
        recorder.setFormat(grabber.getFormat());
        recorder.setAudioBitrate(getBitrate(quality));
        recorder.setAudioChannels(grabber.getAudioChannels());
        recorder.setSampleRate(grabber.getSampleRate());
        recorder.start();

        // 处理音频帧
        while (true) {
            Frame frame = grabber.grab();
            if (frame == null) {
                break;
            }

            recorder.record(frame);
        }

        // 关闭资源
        recorder.stop();
        recorder.release();
        grabber.stop();
        grabber.release();

        // 更新上下文
        context.setAttribute("grabber", new FFmpegFrameGrabber("temp_compress.mp3"));
        log.info("Audio compression completed");
        return null;
    }

    private int getBitrate(String quality) {
        switch (quality.toLowerCase()) {
            case "low":
                return 64000;
            case "medium":
                return 128000;
            case "high":
                return 192000;
            case "veryhigh":
                return 256000;
            default:
                return 128000;
        }
    }
    @Override
    public String getStepName() {
        return "AudioCompress";
    }
} 